<?php

session_start();
include 'connectBDD.php';

if (isset($_POST['formulaire'])) { //Teste d'utilisation du formulare
    if (!empty($_POST["log"]) && !empty($_POST["pass"])) { //Teste que tous les champs ont bien été remplis
        $res = mysql_query("select login, password, type, avatar_path from user where login = '" . addslashes($_POST['log']) . "'") or die(mysql_error());

        if ($row = mysql_fetch_array($res)) { //si le login est trouve
            if (md5($_POST['pass']) == $row['password']) {
                $_SESSION['connecte'] = 'ok';
                $_SESSION['password'] = $row['password'];
                $_SESSION['login'] = $row['login'];
                $_SESSION['type'] = $row['type'];
                $_SESSION['image_profile'] = $row['avatar_path'];
                $precedente = $_SERVER['HTTP_REFERER'];

                $tabUrl = parse_url($precedente);
                $fichier = basename($tabUrl["path"]);
                if ($fichier == 'erreurAuthentification.php') {
                    header("location:index.php");
                } else {
                    header("location:" . $precedente);
                }
            } else {
                $_SESSION['erreur'] = "Le mot de passe ne correspond pas avec le login entré.";
                header('Location: erreurAuthentification.php');
            }
        } else {           //TODO: gérer l'erreur comme il faut (page d'erreur)
            $_SESSION['erreur'] = "login introuvable.";
            header('Location: erreurAuthentification.php');
        }
    }
}

if (isset($_SESSION['connecte']) && $_SESSION['connecte'] == 'ok') {
    echo '<div id="loginBlock">
                    <div id="msgBienvenue"><span>Bienvenue ' . $_SESSION['login'] . '</span>
                        <span><a href="deconnexion.php">[se deconnecter]</a></span>
                    </div>
                    <div id="monCompte"><a href="monCompte.php">Mon compte</a></div>
                   </div>';
} else {
    print('<form action="index.php" method="post">
                        <div id="loginBlock">
                                    Login :</label><input type="text" name="log" value="">
                                    Mot de passe :</label><input type="password" name="pass" value="" id="password">
                            <input type="hidden" name="formulaire" value="ok">
                            <input type="submit" value="Connexion"/>
                            <a href="creationCompte.php">[S\'inscrire]</a>
                        </div>
                    </form>');
}
?>